import uvicorn
import fastapi_cdn_host

from pathlib import Path
from loguru import logger
from typing import AsyncContextManager
from contextlib import asynccontextmanager

from fastapi import FastAPI
from fastapi.staticfiles import StaticFiles
from fastapi.middleware.cors import CORSMiddleware

from routers import action_router
from data.global_var import FASTAPI_HOST, FASTAPI_PORT, STORAGE_DIR, FASTAPI_LOG_LEVEL

app = FastAPI()


# 启动微信 和 itchat后台监听消息
@asynccontextmanager
async def lifespan(app: FastAPI) -> AsyncContextManager[None]:
    # "启动前执行"
    logger.info("启动FastAPI")
    # 配置存储目录, 创建存储目录(如果不存在)
    Path(STORAGE_DIR).mkdir(parents=True, exist_ok=True)
    yield
    # "关闭后前执行"
    logger.info("关闭FastAPI")


# 启动fastapi框架
def start_fastapi(is_thread=False):
    app = FastAPI(lifespan=lifespan, itle="Fastapi Web", description="Fastapi Web 示例项目", version="1.0.0")
    fastapi_cdn_host.patch_docs(app)
    # 挂载静态文件夹
    app.mount("/static", StaticFiles(directory="data/static"), name="static")
    # 设置允许跨域请求
    app.add_middleware(
        CORSMiddleware,
        allow_origins=["*"],  # 允许所有来源
        allow_credentials=True,  # 允许cookie
        allow_methods=["*"],  # 允许所有方法
        allow_headers=["*"],  # 允许所有头部
    )

    # 添加路由器并设置前缀和标签
    # app.include_router(search_page_router, prefix='/searchpage/wxhelper', tags=["查询功能页面"])
    app.include_router(action_router, tags=["动作功能页面"])

    # 启动fastapi
    if is_thread:
        # 子线程启动fastapi
        import threading
        t = threading.Thread(target=uvicorn.run, args=(app,),
                             kwargs={'host': FASTAPI_HOST, 'port': FASTAPI_PORT,
                                     'log_level': FASTAPI_LOG_LEVEL.lower()})
        t.daemon = True  # 守护线程，主线程结束时，子线程也结束
        t.start()
    else:
        uvicorn.run(app, host=FASTAPI_HOST, port=FASTAPI_PORT, log_level=FASTAPI_LOG_LEVEL.lower())


if __name__ == "__main__":
    start_fastapi()
